package com.pvdnc.nsocket.client;

import com.pvdnc.nsocket.EndPoint;
import com.pvdnc.nsocket.init.CSInitializer;
import com.pvdnc.nsocket.protocol.base.Packet;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

public abstract class BaseClient extends CSInitializer {
    public BaseClient(EndPoint endPoint) {
        super(endPoint);
    }

    private Bootstrap getDefault(){

        Bootstrap bootstrap = new Bootstrap();
        bootstrap
                .group(mClientLoop)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true);
        bootstrap.handler(this);

        return bootstrap;
    }

    public abstract void onConnected();

    public void doConnect() {
        Bootstrap bootstrap = getDefault();
        bootstrap.connect(getHost(), getPort()).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess())
                    throw new IllegalStateException("fail to connect", future.cause());
                setChannel(future.channel());
                onConnected();
            }
        });
    }
}
